import { pick, isEqual, isEmpty } from 'lodash-es';
import { LayerInfoFE } from '@/pages/TemplateEditor/interface';
import { floatToInt } from '@/pages/TemplateEditor/components/Editor/components/TemplateEffect/utils';
import { LayerTypeBE } from '@/pages/TemplateEditor/components/Editor/components/TemplateEffect/constant';

export const isLayerModified = (
  oldLayer: LayerInfoFE,
  newLayer: fabric.Object
): boolean => {
  if (isEmpty(oldLayer) || isEmpty(newLayer)) {
    return false;
  }

  // todo：初始化的没有scale，但是后面的有
  const oldInfo = pick(oldLayer, ['width', 'height', 'top', 'left', 'angle']);

  const newInfo = getNewLayerInfo(newLayer);

  return !isEqual(oldInfo, newInfo);
};

export const objPropsToInt = <T extends Record<any, any>>(
  obj: T
): Record<keyof T, number> => {
  const res = {} as Record<keyof T, number>;

  for (const key in obj) {
    res[key] = floatToInt(obj[key]);
  }

  return res;
};

export const getNewLayerInfo = (
  newLayer: fabric.Object
): Record<'left' | 'top' | 'angle' | 'width' | 'height', number> => ({
  left: newLayer.left,
  top: newLayer.top,
  angle: newLayer.angle,
  // layer的width和height数据需要转换
  width: newLayer.getScaledWidth(),
  height: newLayer.getScaledHeight()
});

export const needRealTimePreview = (
  oldLayerData: LayerInfoFE,
  newLayerData: LayerInfoFE
): boolean =>
  oldLayerData.data.type === LayerTypeBE.Text &&
  (oldLayerData.height !== newLayerData.height ||
    oldLayerData.width !== newLayerData.width);
